const { getUserInfo } = require('@/service/user')

const {
  userDoesNotExist,
  invalidPassword,
  userLoginError,
  notAdministrator,
  userAlreadyExited,
  userFormateError
} = require('@/constant/errType')
const bcrypt = require('bcryptjs')

// 注册验证用户名密码为必填
const userValidator = async (ctx, next) => {
  const {username, password} = ctx.request.body
  if (!username || !password) {
    ctx.app.emit('error', userFormateError, ctx)
    return
  }
  return next()
}

// 验证用户是否存在
const verifyUser = async (ctx, next) => {
  const {username} = ctx.request.body
  try {
    const res = await getUserInfo({username})
    if (res) {
      ctx.app.emit('error', userAlreadyExited, ctx)
      return
    }
  } catch(err) {
    ctx.app.emit('error', userRegisterError, ctx)
    return
  }
  return next()
}

// 加密
const bcrpytPassword = async (ctx, next) => {
  const { password } = ctx.request.body
  const salt = bcrypt.genSaltSync(10)
  const hash = bcrypt.hashSync(password, salt)
  ctx.request.body.password = hash
  await next()
}

// 登录验证
const verifyLogin = async (ctx, next) => {
  const {username, password} = ctx.request.body
  try {
    // 1. 判断用户是否存在(不存在:报错)
    const res = await getUserInfo({username})
    if (!res) {
      ctx.app.emit('error', userDoesNotExist, ctx)
      return
    }
    // 2. 密码是否匹配(不匹配: 报错)
    if(!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit('error', invalidPassword, ctx)
      return
    }
  } catch (err) {
    // 用户登录错误
    return ctx.app.emit('error', userLoginError, ctx)
  }
  await next()
}
// 是否是管理员
const isManger = async (ctx, next) => {
  const {user_level} = ctx.user // token里面存的数据
  if (user_level > 0) {
    return ctx.app.emit('error', notAdministrator, ctx)
  }
  await next()
}

module.exports = {
  verifyLogin,
  bcrpytPassword,
  verifyUser,
  userValidator,
  isManger
}